package controller.user;

import cn.smbms.pojo.User;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: SMBMS-two
 * @description:
 * @author: Mr.peng
 * @create: 2020-05-23 15:56
 **/
@Controller
public class Login extends HttpServlet {
//    @Resource
//    private UserService userService;

    @RequestMapping("/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        //ApplicationContext context = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
       UserService userService = context.getBean("user", UserService.class);
        System.out.println("login ============1 ");
        //获取用户名和密码
        String userCode = request.getParameter("userCode");
        String userPassword = request.getParameter("userPassword");
        //调用service方法，进行用户匹配
        //UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);
        if (null != user) {//登录成功
            //放入session
            request.getSession().setAttribute(Constants.USER_SESSION, user);
            //页面跳转（frame.jsp）
           // response.sendRedirect("jsp/frame.jsp");
            return "jsp/frame";
        } else {
            //页面跳转（login.jsp）带出提示信息--转发
            //request.setAttribute("error", "用户名或密码不正确");
            throw new RuntimeException("用户名或密码不正确");
            //request.getRequestDispatcher("login.jsp").forward(request, response);
           // return "login";
        }
    }

//    局部处理异常
//    @ExceptionHandler(value = {RuntimeException.class})
//    public String hand(RuntimeException e,HttpServletRequest req){
//        req.setAttribute("e",e);
//        return "index";
//    }

}
